const { Router } = require("express")
const express = require("express")
const route = express.Router()
const md5 = require("md5")
const { jwtEncode } = require("../utils/jwt")
// 引入数据库集合对象
const adminModel = require("../db/model/adminModel")

route.post("/login", async (req, res) => {
  const { adminName, password } = req.body
  // 通过拿到的数据去数据库里查找
  const findResult = await adminModel.findOne({
    adminName,
    password: md5(password + '123')
  })
  try {
    // 如果没找到
    if (!findResult) {
      return res.send({
        code: 10002,
        msg: "登录失败,用户账号或密码输入错误",
        data: null
      })
    }
    // 如果找到了,根据封装的jwt,生成token响应给用户
    const token = jwtEncode(findResult.adminName, "666")
    // console.log(token);
    // 登录成功以后把数据库当前的用户状态改为1
    await adminModel.updateOne({ adminName }, {
      $set: {
        status: 1
      }
    })
    res.send({
      code: 10000,
      msg: "登录成功",
      data: {
        token
      }
    })
  } catch (e) {
    res.send({
      code: 10001,
      msg: "登录异常" + e.message,
      data: null
    })
  }
})

module.exports = route;